<?php
namespace app\api\controller;

use app\api\model\Echarts;
use app\api\model\Usage as ModelUsage;
use app\home\model\Article;
use app\home\model\Demand;
use app\home\model\News;
use app\home\model\Supply;
use think\facade\Db;

class Usage
{
    public function index()
    {
        
    }
    public function getSpiderUsage()
    {
        
        $chart = Echarts::field('value')->where([
            'chart'=>'spider_usage',
            'add_time'=>date('Y-m-d', strtotime('-1 day')),
        ])->find();
        if (!empty($chart)){
            return json(json_decode($chart['value']));
        }

        $data = [
            [
                'name' => '百度蜘蛛',
                'value' => 0,
            ],
            [
                'name' => '谷歌蜘蛛',
                'value' => 0,
            ],
            [
                'name' => '360蜘蛛',
                'value' => 0,
            ],
            [
                'name' => '搜狗蜘蛛',
                'value' => 0,
            ],
            [
                'name' => '必应蜘蛛',
                'value' => 0,
            ],
        ];

        $map = [
            'baidu' => 0,
            'google' => 0, 
            '360' => 0,
            'sougou' => 0,
            'bing' => 0,
        ];
        

        $file = fopen('/wwwroot/172.20.0.8.access.log', 'r');
        // $line = 1000;
        $pos = -2;
        $ch = '';
        $content = '';
        $date_reg = '/\[([^\]]*)\]/';
        $today = date('Y-m-d 00:00:00', time());
        $today = strtotime($today);
        $flag = false;
        while(true){
            while ($ch != "\n"){
                fseek($file, $pos, SEEK_END);
                $ch = fgetc($file);
                $pos--;
            }
            $ch = '';
            $content = fgets($file);
            // $line--;
            
            preg_match($date_reg, $content, $a_match);
            if (count($a_match) > 1){
                $date = $a_match[1];
            }
            

            $date = date('Y-m-d 00:00:00', strtotime($date));
            //时间判断
            // echo $date. '  '. strtotime($date). '  ' .($today - strtotime($date)) .PHP_EOL;
            

            $time_offset = $today - strtotime($date);

            if ($time_offset < 0){
                continue;
            }else if($time_offset > 86400){
                $flag = true;
                break;
            }else if ($time_offset == 86400){
                // $line++;
            }

            //排除多余记录
            if (strstr($content, '301') || strstr($content, '404') || strstr($content, '500'))continue;
            if (strstr($content, 'Jinkou') || strstr($content, 'Qiugou') || strstr($content, '/Sell/'))continue;
            //爬虫记录
            if (strstr($content, 'Baiduspider')) $map['baidu'] += 1;
            if (strstr($content, 'Googlebot')) $map['google'] += 1;
            if (strstr($content, '360Spider') || strstr($content, 'haosouspider')) $map['360'] += 1;
            if (strstr($content, 'Sogou') || strstr($content, 'sipder')) $map['baidu'] += 1;
            if (strstr($content, 'bingbot')) $map['bing'] += 1;
            
        }
        fclose($file);
        $data[0]['value'] = $map['baidu'];
        $data[1]['value'] = $map['google'];
        $data[2]['value'] = $map['360'];
        $data[3]['value'] = $map['sougou'];
        $data[4]['value'] = $map['bing'];


        $chart = new Echarts;
        $chart->save([
            'chart'=>'spider_usage',
            'value'=>json_encode([
                'data' => $data,
                'today' => date('Y-m-d', $today),
                'yestoday' => date('Y-m-d', strtotime('-1 day')),
                'flag' => $flag,
            ], JSON_UNESCAPED_SLASHES),
            'add_time'=>date('Y-m-d', strtotime('-1 day')),
            'update_time'=>date('Y-m-d', time()),
            'other'=>''
        ]);
        return json([
            'data' => $data,
            'today' => date('Y-m-d', $today),
            'yestoday' => date('Y-m-d', strtotime('-1 day')),
            'flag' => $flag,
        ]);
    }
    public function getLogLength()
    {
        $fp=fopen('/wwwroot/172.17.0.2.access.log', "r");
        $i=0;
        while(!feof($fp)) {
          //每次读取2M
          if($data=fread($fp,1024*1024*2)){
            //计算读取到的行数
            $num=substr_count($data,"\n");
            $i+=$num;
          }
        }
        fclose($fp);
        return $i;
      }
      

    
      protected static function getFiles(){
        $handler = opendir('/wwwroot');
        $log = [];
        while (($filename = readdir($handler)) !== false) {//务必使用!==，防止目录下出现类似文件名“0”等情况
            if ($filename != "." && $filename != "..") {
                if(strstr($filename, 'access.log')){
                    array_push($log, $filename);
                }
            }
        }
        closedir($handler);
        return $log;
    }
    public function getSpiderAccessData()
    {
        $spider = [
            'baidu'     => 0,
            '360'       => 0,
            'google'    => 0,
            'sougou'    => 0,
            'biyin'     => 0,
        ];
        foreach (self::getFiles() as $log_file){
            while(!feof($log_file)){
                $line = fgets($log_file);
            }
        }
    }
    public function getAccessPageUsage()
    {
        $date_1 = date('Y-m-d', strtotime('-1 day'));
        // $date_2 = date('Y-m-d', strtotime('-2 day'));
        // $date_3 = date('Y-m-d', strtotime('-3 day'));
        // $date_4 = date('Y-m-d', strtotime('-4 day'));
        // $date_5 = date('Y-m-d', strtotime('-5 day'));
        $usage = new ModelUsage;
        $data = [
            $usage->where('access_page','Nd')->where('access_time', $date_1)->count(),
            $usage->where('access_page', 'Pd')->where('access_time', $date_1)->count(),
            $usage->where('access_page', 'Dd')->where('access_time', $date_1)->count(),
            $usage->where('access_page', 'Spd')->where('access_time', $date_1)->count(),
            $usage->where('access_page', 'Other')->where('access_time', $date_1)->count(),
        ];
        return json([
            'data' => $data,
            'yestoday' => $date_1,
        ]);
    }
    public function pushLink()
    {
        $data = request()->param();
        if (empty($data))return json(['error'=>400, 'message'=>'empty param'], 400);
        $type = $data['type'];
        $operation = $data['operation'];
        $push_link = [];
        switch($operation){
            case '最新':
                $operation = true;
                break;
            case '随机':
                $operation = false;
        }
        $len = (int)(2000/count($type));
        foreach($type as $t){
            switch($t){
                case "资讯":
                    if ($operation){
                        $link = News::field('hash_str')->order('addtime desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_news  ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "文章":
                    if ($operation){
                        $link = Article::field('hash_str')->order('addtime desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_article ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "供应":
                    if ($operation){
                        $link = Supply::field('hash')->order('add_time desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash FROM stpc_qzz_provider ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "需求":
                    if ($operation){
                        $link = Demand::field('hash_str')->order('add_time desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_demand ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
            }
        }

        $api = 'http://data.zz.baidu.com/urls?site=www.quzizhu.com&token=So2gPzzYfVGQSiY0';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $push_link),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = json_decode(curl_exec($ch));

        
        return json($result);
    }
    public function createSitemap()
    {
        $data = request()->param();
        if (empty($data))return json(['error'=>400, 'message'=>'empty param'], 400);
        $type = $data['type'];
        $operation = $data['operation'];
        $push_link = [];
        switch($operation){
            case '最新':
                $operation = true;
                break;
            case '随机':
                $operation = false;
        }
        $len = (int)(2000/count($type));
        foreach($type as $t){
            switch($t){
                case "资讯":
                    if ($operation){
                        $link = News::field('hash_str')->order('addtime desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_news  ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "文章":
                    if ($operation){
                        $link = Article::field('hash_str')->order('addtime desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_article ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "供应":
                    if ($operation){
                        $link = Supply::field('hash')->order('add_time desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash FROM stpc_qzz_provider ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
                case "需求":
                    if ($operation){
                        $link = Demand::field('hash_str')->order('add_time desc')->limit($len)->select();
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }else{
                        $sql = "SELECT hash_str FROM stpc_qzz_demand ORDER BY RAND() LIMIT $len";
                        $link = Db::query($sql);
                        foreach($link as $l){
                            $hash = $l['hash_str'];
                            array_push($push_link, "http://www.quzizhu.com/?$hash");
                        }
                    }
                    break;
            }
        }

        $site_map_path = '/wwwroot/public/sitemap.txt';
        if (file_exists($site_map_path)){
            unlink($site_map_path);
        }
        $site_map = fopen($site_map_path, 'w');
        foreach($push_link as $link){
            fwrite($site_map, "$link\n");
        }
        fclose($site_map);
    }
}
